var express = require('express');
var path = require('path');
//var favicon = require('serve-favicon');
var logger = require('morgan');
var ejs=require('ejs');
var donggu = require('./routes/donggu');
var comment = require('./routes/comment');

var session = require('express-session');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var ueditor = require("ueditor");
var app = express();




app.all('*', function(req, res, next) {
    res.header('Access-Control-Allow-Origin', "http://127.0.0.1:9090");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header('Access-Control-Allow-Credentials', true);
    res.header("X-Powered-By",' 3.2.1');
    res.header("Content-Type", "application/json;charset=utf-8");
    res.header("Content-Type", "multipart/form-data;charset=utf-8");
    next();
});

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('.html',ejs.__express);
app.set('view engine', 'html');
// uncomment after placing your favicon in /public
app.use(logger('dev'));
app.use(bodyParser.json({limit: '3mb'})); // for parsing application/json
app.use(bodyParser.urlencoded({limit: '3mb', extended: true })); // for parsing application/x-www-form-urlencoded
app.use(express.static(path.join(__dirname, 'views')));

app.use("/static/ueditor/ue", ueditor(path.join(__dirname, 'views/static'), function (req, res, next) {
    //客户端上传文件设置
    var imgDir = '../upload/images/'
    var ActionType = req.query.action;
    if (ActionType === 'uploadimage' || ActionType === 'uploadfile' || ActionType === 'uploadvideo') {
        var file_url = imgDir;//默认图片上传地址
        /*其他上传格式的地址*/
        if (ActionType === 'uploadfile') {
            file_url = '../upload/file/'; //附件
        }
        if (ActionType === 'uploadvideo') {
            file_url = '../upload/video/'; //视频
        }
        res.ue_up(file_url); //你只要输入要保存的地址 。保存操作交给ueditor来做
        res.setHeader('Content-Type', 'text/html');
    }
    //  客户端发起图片列表请求
    else if (req.query.action === 'listimage') {
        var dir_url = imgDir;
        res.ue_list(dir_url); // 客户端会列出 dir_url 目录下的所有图片
    }
    // 客户端发起其它请求
    else {
        // console.log('config.json')
        res.setHeader('Content-Type', 'application/json');
        res.redirect('/static/ueditor/nodejs/config.json');
    }
}));


app.use('/donggu', donggu);
app.use('/comment', comment);

app.use(function (req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

app.use(function (err, req, res, next) {
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};
    res.status(err.status || 500);
    //res.render('error');
});



module.exports = app;
